from datetime import datetime, timedelta, timezone
import jwt

from app.schemas.login import JWTPayload
from app.schemas.login import *
from app.models.admin import User
from app.settings.config import settings
from app.utils.password import get_password_hash, verify_password,generate_password


def create_access_token(*, data: JWTPayload):
    payload = data.model_dump().copy()
    encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return encoded_jwt

def jwt_decode(token, verify_exp=True):
    """
    jwt解密
    :param token:
    :param verify_exp:
    :return:
    """

    # token解密
    payload = jwt.decode(
        token,
        settings.SECRET_KEY,
        algorithms=settings.JWT_ALGORITHM,
        # options={"verify_exp": verify_exp}
    )
    return payload

def issuance_of_jwt(user: User):
    access_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
    expire = datetime.now(timezone.utc) + access_token_expires
    refresh_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 10) # 10倍
    refreshexpire = datetime.now(timezone.utc) + refresh_token_expires
    jid = get_password_hash(generate_password())
    data = JWTOut(
        access_token=create_access_token(
            data=JWTPayload(
                user_id=user.id,
                username=user.username,
                jid=jid,
                is_superuser=user.is_superuser,
                exp=expire,
            )
        ),
        refresh_token=create_access_token(
            data=JWTPayload(
                user_id=user.id,
                username=user.username,
                is_superuser=user.is_superuser,
                exp=refreshexpire,
                refresh_key=get_password_hash(f"{user.id}{jid}{user.username}"),
            )
        ),
        username=user.username,
        expires_in=expire.timestamp(),
    )
    return data
    